package com.mail.config.database;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
/**
 * 切面类
 * @author wp
 * 当使用readOnlyConnection这个注解的时候就执行这个切面类中的proceed方法，强制切换数据源
 */
@Aspect
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {
	public static final Logger LOGGER = LoggerFactory.getLogger(ReadOnlyConnectionInterceptor.class);
	/**切入点*/
	@Around("@annotation(readOnlyConnection)")
	public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
		try {
			LOGGER.info("set database connection to read only");
			DataSourceContextHolder.setDateBaseType(DataSourceContextHolder.DataBaseType.SLAVE);
			Object result = proceedingJoinPoint.proceed();
		    return result;
		} finally {
			DataSourceContextHolder.clearDataBaseType();
			LOGGER.info("restore database connection");
		}
	}
	@Override
	public int getOrder() {
		return 0;
	}
}